package com.lanou3g.hw0517.model;


import com.lanou3g.hw0517.pojo.User;
import com.lanou3g.hw0517.util.JDBCUtil;
import com.lanou3g.hw0517.util.MyResultSet;
import com.lanou3g.hw0517.util.MyStatement;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Model {
    //判断数据库中是否有某一个用户名
    //uesrname 要判断的用户名
    //true:数据库中有该用户名;false:数据库中没有该用户
    public boolean hasUsername(String username) {

        String sql = "SElECT COUNT(*) FROM `users` WHERE username= ?";
        MyStatement statement = JDBCUtil.getPreStatement(sql);
        statement.setString(1, username);
        //执行完这行语句后,就不会自动的关闭资源
        MyResultSet rs = statement.executeQuery();
        rs.next();
        int count = rs.getInt(1);
        rs.close();
        JDBCUtil.closeResource(statement);
        return count > 0;
    }

    //注册
    public boolean register(String username, String pwd, String nickname, String hobby, String gender) {
        String sql = "INSERT INTO `users` (username, pwd, nickname,hobby,gender)" +
                " VALUES ( ? , ? , ? , ? , ? )";
        MyStatement statement = JDBCUtil.getPreStatement(sql);
        statement.setString(1, username);
        statement.setString(2, pwd);
        statement.setString(3, nickname);
        statement.setString(4, hobby);
        statement.setString(5, gender);
        //不需要结果集的执行,可以实现自动关闭资源
        int rows = statement.executeUpdate();
        return rows > 0;
    }

    /**
     * 登录
     *
     * @param username 用户名
     * @param pwd      密码
     * @return 登陆成功:返回装着用户信息的user对象
     * 登录失败:return null
     */
    public User login(String username, String pwd) {
        //1.查一下 是否有这个用户
        //条件是用户名和密码都匹配上
        String checkLogin = "SELECT * FROM `users` WHERE" +
                " username = ? AND pwd = ?";

        PreparedStatement statement = JDBCUtil.getPreStatement(checkLogin);

        try {
            //设置值
            statement.setString(1, username);
            statement.setString(2, pwd);
            ResultSet rs = statement.executeQuery();//执行这个方法
            User user = null;
            if (rs.next()) {
                user = new User();
                String dbUsername = rs.getString("username");
                String dbPwd = rs.getString("pwd");
                user.setPwd(dbPwd);
                user.setUsername(dbUsername);
            }
            rs.close();
            JDBCUtil.closeResource(statement);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;

    }

}